{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tutorial 2 of 3: Digging Deeper into OpenPNM\n",
    "\n",
    "This tutorial will follow the same outline as **Getting Started**, but will dig a little bit deeper at each step to reveal the important features of OpenPNM that were glossed over previously.\n",
    "\n",
    "**Learning Objectives**\n",
    "\n",
    "* Explore different network topologies, and learn some handy topological query methods\n",
    "* Create a *heterogeneous* domain with different geometrical properties in different regions\n",
    "* Learn about data exchange between objects\n",
    "* Utilize pore-scale models for calculating properties of all types\n",
    "* Propagate changing geometrical and thermo-physical properties to all dependent properties\n",
    "* Calculate the permeability tensor for the stratified media\n",
    "* Use the Workspace Manager to save and load a simulation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Building a Cubic Network\n",
    "\n",
    "As usual, start by importing the OpenPNM and Scipy packages:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:09.270679Z",
     "iopub.status.busy": "2021-06-24T11:25:09.269060Z",
     "iopub.status.idle": "2021-06-24T11:25:09.872495Z",
     "shell.execute_reply": "2021-06-24T11:25:09.871082Z"
    }
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import scipy as sp\n",
    "import openpnm as op\n",
    "%config InlineBackend.figure_formats = ['svg']\n",
    "np.random.seed(10)\n",
    "ws = op.Workspace()\n",
    "ws.settings[\"loglevel\"] = 40"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's generate a cubic network again, but with a different connectivity:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:09.882005Z",
     "iopub.status.busy": "2021-06-24T11:25:09.880606Z",
     "iopub.status.idle": "2021-06-24T11:25:09.893052Z",
     "shell.execute_reply": "2021-06-24T11:25:09.894205Z"
    }
   },
   "outputs": [],
   "source": [
    "pn = op.network.Cubic(shape=[20, 20, 10], spacing=0.0001, connectivity=14)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* This **Network** has pores distributed in a cubic lattice, but connected to diagonal neighbors due to the ``connectivity`` being set to 14 (the default is 6 which is orthogonal neighbors).  The various options are outlined in the **Cubic** class's documentation which can be viewed with the Object Inspector in Spyder.\n",
    "\n",
    "* OpenPNM includes several other classes for generating networks including random topology based on Delaunay tessellations (**Delaunay**).\n",
    "\n",
    "* It is also possible to `import networks <data_io>`_ from external sources, such as networks extracted from tomographic images, or that networks generated by external code."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Initialize and Build *Multiple* Geometry Objects\n",
    "\n",
    "One of the main functionalities of OpenPNM is the ability to assign drastically different geometrical properties to different regions of the domain to create heterogeneous materials, such as layered structures.  To demonstrate the motivation behind this feature, this tutorial will make a material that has different geometrical properties on the top and bottom surfaces compared to the internal pores.  We need to create one **Geometry** object to manage the top and bottom pores, and a second to manage the remaining internal pores:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:09.904878Z",
     "iopub.status.busy": "2021-06-24T11:25:09.903440Z",
     "iopub.status.idle": "2021-06-24T11:25:09.914003Z",
     "shell.execute_reply": "2021-06-24T11:25:09.915127Z"
    }
   },
   "outputs": [],
   "source": [
    "Ps1 = pn.pores(['top', 'bottom'])\n",
    "Ts1 = pn.find_neighbor_throats(pores=Ps1, mode='union')\n",
    "geom1 = op.geometry.GenericGeometry(network=pn, pores=Ps1, throats=Ts1, name='boundaries')\n",
    "Ps2 = pn.pores(['top', 'bottom'], mode='not')\n",
    "Ts2 = pn.find_neighbor_throats(pores=Ps2, mode='xnor')\n",
    "geom2 = op.geometry.GenericGeometry(network=pn, pores=Ps2, throats=Ts2, name='core')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* The above statements result in two distinct **Geometry** objects, each applying to different regions of the domain.  ``geom1`` applies to only the pores on the top and bottom surfaces (automatically labeled 'top' and 'bottom' during the network generation step), while ``geom2`` applies to the pores 'not' on the top and bottom surfaces.\n",
    "\n",
    "* The assignment of throats is more complicated and illustrates the ``find_neighbor_throats`` method, which is one of the more useful `topological query methods <topology>`_ on the **Network** class.  In both of these calls, all throats connected to the given set of pores (``Ps1`` or ``Ps2``) are found; however, the ``mode`` argument alters which throats are returned.  The terms ``'union'`` and ``'intersection'`` are used in the \"set theory\" sense, such that ``'union'`` returns *all* throats connected to the pores in the supplied list, while ``'intersection'`` returns the throats that are *only* connected to the supplied pores.  More specifically, if pores 1 and 2 have throats [1, 2] and [2, 3] as neighbors, respectively, then the ``'union'`` mode returns [1, 2, 3] and the ``'intersection'`` mode returns [2].  A detailed description of this behavior is given in :ref:`topology`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Assign Static Seed values to *Each* Geometry\n",
    "\n",
    "In :ref:`getting_started` we only assigned 'static' values to the **Geometry** object, which we calculated explicitly.  In this tutorial we will use the *pore-scale models* that are provided with OpenPNM.  To get started, however, we'll assign static random seed values between 0 and 1 to each pore on both **Geometry** objects, by assigning random numbers to each Geometry's ``'pore.seed'`` property:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:09.924616Z",
     "iopub.status.busy": "2021-06-24T11:25:09.923189Z",
     "iopub.status.idle": "2021-06-24T11:25:09.926262Z",
     "shell.execute_reply": "2021-06-24T11:25:09.927395Z"
    }
   },
   "outputs": [],
   "source": [
    "geom1['pore.seed'] = np.random.rand(geom1.Np)*0.5 + 0.2\n",
    "geom2['pore.seed'] = np.random.rand(geom2.Np)*0.5 + 0.2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Each of the above lines produced an array of different length, corresponding to the number of pores assigned to each **Geometry** object.  This is accomplished by the calls to ``geom1.Np`` and ``geom2.Np``, which return the number of pores on each object.\n",
    "* Every Core object in OpenPNM possesses the same set of methods for managing their data, such as counting the number of pore and throat values they represent; thus, ``pn.Np`` returns 1000 while ``geom1.Np`` and ``geom2.Np`` return 200 and 800 respectively."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Accessing Data Distributed Between Geometries\n",
    "\n",
    "The segmentation of the data between separate Geometry objects is essential to the management of pore-scale models, although it does create a complication: it's not easy to obtain a single array containing *all* the values of a given property for the whole network.  It is technically possible to piece this data together manually since we know the locations where each **Geometry** object applies, but this is tedious so OpenPNM provides a shortcut.  First, let's illustrate the manual approach using the ``'pore.seed'`` values we have defined:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:09.937726Z",
     "iopub.status.busy": "2021-06-24T11:25:09.936281Z",
     "iopub.status.idle": "2021-06-24T11:25:09.943824Z",
     "shell.execute_reply": "2021-06-24T11:25:09.944991Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "seeds = np.zeros_like(pn.Ps, dtype=float)\n",
    "seeds[pn.pores(geom1.name)] = geom1['pore.seed']\n",
    "seeds[pn.pores(geom2.name)] = geom2['pore.seed']\n",
    "print(np.all(seeds > 0))  # Ensure all zeros are overwritten"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following code illustrates the shortcut approach, which accomplishes the same result as above in a single line:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:09.953100Z",
     "iopub.status.busy": "2021-06-24T11:25:09.952095Z",
     "iopub.status.idle": "2021-06-24T11:25:09.957305Z",
     "shell.execute_reply": "2021-06-24T11:25:09.956398Z"
    }
   },
   "outputs": [],
   "source": [
    "seeds = pn['pore.seed']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* This shortcut works because the ``pn`` dictionary does not contain an array called ``'pore.seed'``, so all associated **Geometry** objects are then checked for the requested array(s).  If it is found, then OpenPNM essentially performs the *interleaving* of the data as demonstrated by the manual approach and returns all the values together in a single full-size array.  If it is not found, then a standard *KeyError* message is received.\n",
    "* This exchange of data between **Network** and **Geometry** makes sense if you consider that **Network** objects act as a sort of master object relative **Geometry** objects.  **Networks** apply to *all* pores and throats in the domain, while **Geometries**  apply to subsets of the domain, so if the **Network** needs some values from all pores it has direct access."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Add Pore Size Distribution Models to Each Geometry\n",
    "\n",
    "Pore-scale models are mathematical functions that are applied to each pore (or throat) in the network to produce some local property value.  Each of the modules in OpenPNM (Network, Geometry, Phase and Physics) have a \"library\" of pre-written models located under \"models\" (i.e. *Geometry.models*).  Below this level, the models are further categorized according to what property they calculate, and there are typical 2-3 models for each.  For instance, under ``Geometry.models.pore_diameter`` you will see ``random``, ``normal`` and ``weibull`` among others.\n",
    "\n",
    "Pore size distribution models are assigned to each Geometry object as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:09.968116Z",
     "iopub.status.busy": "2021-06-24T11:25:09.966942Z",
     "iopub.status.idle": "2021-06-24T11:25:10.114466Z",
     "shell.execute_reply": "2021-06-24T11:25:10.113208Z"
    }
   },
   "outputs": [],
   "source": [
    "geom1.add_model(propname='pore.diameter',\n",
    "                model=op.models.geometry.pore_size.normal,\n",
    "                scale=0.00001, loc=0.00005,\n",
    "                seeds='pore.seed')\n",
    "geom2.add_model(propname='pore.diameter',\n",
    "                model=op.models.geometry.pore_size.weibull,\n",
    "                shape=1.2, scale=0.00001, loc=0.00005,\n",
    "                seeds='pore.seed')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Pore-scale models tend to be the most complex (i.e. confusing) aspects of OpenPNM, so it's worth dwelling on the important points of the above two commands:\n",
    "\n",
    "* Both ``geom1`` and ``geom2`` have a ``models`` attribute where the parameters specified in the ``add`` command are stored for future use if/when needed.  The ``models`` attribute actually contains a **ModelsDict** object which is a customized dictionary for storing and managing this type of information.\n",
    "\n",
    "* The ``propname`` argument specifies which property the model calculates.  This means that the numerical results of the model calculation will be saved in their respective **Geometry** objects as ``geom1['pore.diameter']`` and ``geom2['pore.diameter']``.\n",
    "\n",
    "* Each model stores it's result under the same ``propname`` but these values do not conflict since each **Geometry** object presides over a unique subset of pores and throats.\n",
    "\n",
    "* The ``model`` argument contains a *handle* to the desired function, which is extracted from the *models* library of the relevant *Module* (**Geometry** in this case).  Each **Geometry** object has been assigned a different statistical model, *normal* and *weibull*.  This ability to apply different models to different regions of the domain is reason multiple **Geometry** objects are permitted.  The added complexity is well worth the added flexibility.\n",
    "\n",
    "* The remaining arguments are those required by the chosen *model*.  In the above cases, these are the parameters that define the statistical distribution.  Note that the mean pore size for ``geom1`` will be 20 um (set by ``scale``) while for ``geom2`` it will be 50 um, thus creating the smaller surface pores as intended.  The pore-scale models are well documented regarding what arguments are required and their meaning; as usual these can be viewed with Object Inspector in Spyder."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we've added pore diameter models the each **Geometry** we can visualize the network in Paraview to confirm that distinctly different pore sizes on the surface regions:\n",
    "\n",
    "<img src=\"http://i.imgur.com/5F70ens.png\" style=\"width: 60%\" align=\"left\"/>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Add Additional Pore-Scale Models to Each Geometry\n",
    "\n",
    "In addition to pore diameter, there are several other geometrical properties needed to perform a permeability simulation.  Let's start with throat diameter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.122215Z",
     "iopub.status.busy": "2021-06-24T11:25:10.120803Z",
     "iopub.status.idle": "2021-06-24T11:25:10.136516Z",
     "shell.execute_reply": "2021-06-24T11:25:10.135299Z"
    }
   },
   "outputs": [],
   "source": [
    "geom1.add_model(propname='throat.diameter',\n",
    "                model=op.models.misc.from_neighbor_pores,\n",
    "                prop='pore.diameter',\n",
    "                mode='min')\n",
    "geom2.add_model(propname='throat.diameter',\n",
    "                model=op.models.misc.from_neighbor_pores,\n",
    "                prop='pore.diameter',\n",
    "                mode='min')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.143274Z",
     "iopub.status.busy": "2021-06-24T11:25:10.141859Z",
     "iopub.status.idle": "2021-06-24T11:25:10.152319Z",
     "shell.execute_reply": "2021-06-24T11:25:10.153443Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[5.21639565e-05, 5.83316363e-05],\n",
       "       [5.83316363e-05, 5.63074931e-05],\n",
       "       [5.63074931e-05, 5.92495511e-05],\n",
       "       ...,\n",
       "       [5.95407077e-05, 5.39710315e-05],\n",
       "       [5.31619482e-05, 5.42961235e-05],\n",
       "       [5.21510932e-05, 5.31255512e-05]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pn['pore.diameter'][pn['throat.conns']]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Instead of using statistical distribution functions, the above lines use the ``neighbor`` model which determines each throat value based on the values found ``'pore_prop'`` from it's neighboring pores.  In this case, each throat is assigned the minimum pore diameter of it's two neighboring pores.  Other options for ``mode`` include ``'max'`` and ``'mean'``.\n",
    "\n",
    "We'll also need throat length as well as the cross-sectional area of pores and throats, for calculating the hydraulic conductance model later."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.161635Z",
     "iopub.status.busy": "2021-06-24T11:25:10.160131Z",
     "iopub.status.idle": "2021-06-24T11:25:10.209495Z",
     "shell.execute_reply": "2021-06-24T11:25:10.208232Z"
    }
   },
   "outputs": [],
   "source": [
    "geom1.add_model(propname='throat.hydraulic_size_factors',\n",
    "                model=op.models.geometry.hydraulic_size_factors.spheres_and_cylinders)\n",
    "geom2.add_model(propname='throat.hydraulic_size_factors',\n",
    "                model=op.models.geometry.hydraulic_size_factors.spheres_and_cylinders)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create a Phase Object and Assign Thermophysical Property Models\n",
    "\n",
    "For this tutorial, we will create a generic **Phase** object for water, then assign some pore-scale models for calculating their properties.  Alternatively, we could use the prewritten **Water** class included in OpenPNM, which comes complete with the necessary pore-scale models, but this would defeat the purpose of the tutorial."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.216935Z",
     "iopub.status.busy": "2021-06-24T11:25:10.215495Z",
     "iopub.status.idle": "2021-06-24T11:25:10.218408Z",
     "shell.execute_reply": "2021-06-24T11:25:10.219529Z"
    }
   },
   "outputs": [],
   "source": [
    "water = op.phases.GenericPhase(network=pn)\n",
    "air = op.phases.GenericPhase(network=pn)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that all **Phase** objects are automatically assigned standard temperature and pressure conditions when created.  This can be adjusted:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.226162Z",
     "iopub.status.busy": "2021-06-24T11:25:10.224902Z",
     "iopub.status.idle": "2021-06-24T11:25:10.227509Z",
     "shell.execute_reply": "2021-06-24T11:25:10.228499Z"
    }
   },
   "outputs": [],
   "source": [
    "water['pore.temperature'] = 353  # K"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A variety of pore-scale models are available for calculating **Phase** properties, generally taken from correlations in the literature.  An empirical correlation specifically for the viscosity of water is available:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.235079Z",
     "iopub.status.busy": "2021-06-24T11:25:10.234030Z",
     "iopub.status.idle": "2021-06-24T11:25:10.237738Z",
     "shell.execute_reply": "2021-06-24T11:25:10.238515Z"
    }
   },
   "outputs": [],
   "source": [
    "water.add_model(propname='pore.viscosity',\n",
    "                model=op.models.phases.viscosity.water)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create Physics Objects for Each Geometry\n",
    "\n",
    "**Physics** objects are where geometric information and thermophysical properties are combined to produce the pore and throat scale transport parameters.  Thus we need to create one **Physics** object for *EACH* **Phase** and *EACH* **Geometry**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.247659Z",
     "iopub.status.busy": "2021-06-24T11:25:10.246602Z",
     "iopub.status.idle": "2021-06-24T11:25:10.266775Z",
     "shell.execute_reply": "2021-06-24T11:25:10.265533Z"
    }
   },
   "outputs": [],
   "source": [
    "phys1 = op.physics.GenericPhysics(network=pn, phase=water, geometry=geom1)\n",
    "phys2 = op.physics.GenericPhysics(network=pn, phase=water, geometry=geom2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next add the Hagan-Poiseuille model to both:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.273655Z",
     "iopub.status.busy": "2021-06-24T11:25:10.272261Z",
     "iopub.status.idle": "2021-06-24T11:25:10.298387Z",
     "shell.execute_reply": "2021-06-24T11:25:10.297070Z"
    }
   },
   "outputs": [],
   "source": [
    "mod = op.models.physics.hydraulic_conductance.hagen_poiseuille\n",
    "phys1.add_model(propname='throat.hydraulic_conductance', model=mod)\n",
    "phys2.add_model(propname='throat.hydraulic_conductance', model=mod)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* The same function (``mod``) was passed as the ``model`` argument to both **Physics** objects.  This means that both objects will calculate the hydraulic conductance using the same function.  A model *must* be assigned to both objects in order for the ``'throat.hydraulic_conductance'`` property be defined everywhere in the domain since each **Physics** applies to a unique selection of pores and throats.\n",
    "* The \"pore-scale model\" mechanism was specifically designed to allow for users to easily create their own custom models.  Creating custom models is outlined in :ref:`advanced_usage`."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Accessing Data Distributed Between Multiple Physics Objects\n",
    "\n",
    "Just as **Network** objects can retrieve data from separate **Geometries** as a single array with values in the correct locations, **Phase** objects can retrieve data from **Physics** objects as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.305669Z",
     "iopub.status.busy": "2021-06-24T11:25:10.304304Z",
     "iopub.status.idle": "2021-06-24T11:25:10.307149Z",
     "shell.execute_reply": "2021-06-24T11:25:10.308250Z"
    }
   },
   "outputs": [],
   "source": [
    "g = water['throat.hydraulic_conductance']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Each **Physics** applies to the same subset for pores and throats as the **Geometries** so its values are distributed spatially, but each **Physics** is also associated with a single **Phase** object.  Consequently, only a **Phase** object can to request all of the values within the domain pertaining to itself.\n",
    "* In other words, a **Network** object cannot aggregate the **Physics** data because it doesn't know which **Phase** is referred to.  For instance, when asking for ``'throat.hydraulic_conductance'`` it could refer to water or air conductivity, so it can only be requested by water or air."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pore-Scale Models: The Big Picture\n",
    "\n",
    "Having created all the necessary objects with pore-scale models, it is now time to demonstrate why the OpenPNM pore-scale model approach is so powerful.  First, let's inspect the current value of hydraulic conductance in throat 1 on ``phys1`` and ``phys2``:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.314536Z",
     "iopub.status.busy": "2021-06-24T11:25:10.313316Z",
     "iopub.status.idle": "2021-06-24T11:25:10.315866Z",
     "shell.execute_reply": "2021-06-24T11:25:10.316850Z"
    }
   },
   "outputs": [],
   "source": [
    "g1 = phys1['throat.hydraulic_conductance']  # Save this for later\n",
    "g2 = phys2['throat.hydraulic_conductance']  # Save this for later"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's alter the **Geometry** objects by assigning new random seeds, and adjust the temperature of ``water``."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.324119Z",
     "iopub.status.busy": "2021-06-24T11:25:10.322870Z",
     "iopub.status.idle": "2021-06-24T11:25:10.327577Z",
     "shell.execute_reply": "2021-06-24T11:25:10.328443Z"
    }
   },
   "outputs": [],
   "source": [
    "geom1['pore.seed'] = np.random.rand(geom1.Np)\n",
    "geom2['pore.seed'] = np.random.rand(geom2.Np)\n",
    "water['pore.temperature'] = 370  # K"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So far we have not run the ``regenerate`` command on any of these objects, which means that the above changes have not yet been applied to all the dependent properties.  Let's do this and examine what occurs at each step:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.335475Z",
     "iopub.status.busy": "2021-06-24T11:25:10.334261Z",
     "iopub.status.idle": "2021-06-24T11:25:10.474931Z",
     "shell.execute_reply": "2021-06-24T11:25:10.473360Z"
    }
   },
   "outputs": [],
   "source": [
    "geom1.regenerate_models()\n",
    "geom2.regenerate_models()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These two lines trigger the re-calculation of all the size related models on each **Geometry** object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.481872Z",
     "iopub.status.busy": "2021-06-24T11:25:10.480503Z",
     "iopub.status.idle": "2021-06-24T11:25:10.491502Z",
     "shell.execute_reply": "2021-06-24T11:25:10.490395Z"
    }
   },
   "outputs": [],
   "source": [
    "water.regenerate_models()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This line causes the viscosity to be recalculated at the new temperature. Let's confirm that the hydraulic conductance has NOT yet changed since we have not yet regenerated the **Physics** objects' models:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.498615Z",
     "iopub.status.busy": "2021-06-24T11:25:10.496911Z",
     "iopub.status.idle": "2021-06-24T11:25:10.503150Z",
     "shell.execute_reply": "2021-06-24T11:25:10.502071Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print(np.all(phys1['throat.hydraulic_conductance'] == g1))  # g1 was saved above"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.509644Z",
     "iopub.status.busy": "2021-06-24T11:25:10.508543Z",
     "iopub.status.idle": "2021-06-24T11:25:10.512282Z",
     "shell.execute_reply": "2021-06-24T11:25:10.513108Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print(np.all(phys2['throat.hydraulic_conductance'] == g2) ) # g2 was saved above"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, if we regenerate ``phys1`` and ``phys2`` we can see that the hydraulic conductance will be updated to reflect the new sizes on the **Geometries** *and* the new temperature on the **Phase**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.520731Z",
     "iopub.status.busy": "2021-06-24T11:25:10.519724Z",
     "iopub.status.idle": "2021-06-24T11:25:10.544081Z",
     "shell.execute_reply": "2021-06-24T11:25:10.545189Z"
    }
   },
   "outputs": [],
   "source": [
    "phys1.regenerate_models()\n",
    "phys2.regenerate_models()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.551756Z",
     "iopub.status.busy": "2021-06-24T11:25:10.550325Z",
     "iopub.status.idle": "2021-06-24T11:25:10.555809Z",
     "shell.execute_reply": "2021-06-24T11:25:10.554700Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print(np.all(phys1['throat.hydraulic_conductance'] != g1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.561887Z",
     "iopub.status.busy": "2021-06-24T11:25:10.560635Z",
     "iopub.status.idle": "2021-06-24T11:25:10.565284Z",
     "shell.execute_reply": "2021-06-24T11:25:10.564431Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "print(np.all(phys2['throat.hydraulic_conductance'] != g2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Determine Permeability Tensor by Changing Inlet and Outlet Boundary Conditions\n",
    "\n",
    "The [Getting started Tutorial](intro_to_openpnm_basic.ipynb) already demonstrated the process of performing a basic permeability simulation.  In this tutorial, we'll perform the simulation in all three perpendicular dimensions to obtain the permeability tensor of our heterogeneous anisotropic material."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.571789Z",
     "iopub.status.busy": "2021-06-24T11:25:10.570313Z",
     "iopub.status.idle": "2021-06-24T11:25:10.575167Z",
     "shell.execute_reply": "2021-06-24T11:25:10.575893Z"
    }
   },
   "outputs": [],
   "source": [
    "alg = op.algorithms.StokesFlow(network=pn, phase=water)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Set boundary conditions for flow in the X-direction:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.584804Z",
     "iopub.status.busy": "2021-06-24T11:25:10.583564Z",
     "iopub.status.idle": "2021-06-24T11:25:10.732615Z",
     "shell.execute_reply": "2021-06-24T11:25:10.732034Z"
    }
   },
   "outputs": [],
   "source": [
    "alg.set_value_BC(values=202650, pores=pn.pores('back'))\n",
    "alg.set_value_BC(values=101325, pores=pn.pores('front'))\n",
    "alg.run()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The resulting pressure field can be seen using Paraview:\n",
    "\n",
    "<img src=\"http://i.imgur.com/ugX0LFG.png\" style=\"width: 60%\" align=\"left\"/>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To determine the permeability coefficient we must find the flow rate through the network to use in Darcy's law.  The **StokesFlow** class (and all analogous transport algorithms) possess a ``rate`` method that calculates the net transport through a given set of pores:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.737100Z",
     "iopub.status.busy": "2021-06-24T11:25:10.736478Z",
     "iopub.status.idle": "2021-06-24T11:25:10.744895Z",
     "shell.execute_reply": "2021-06-24T11:25:10.744303Z"
    }
   },
   "outputs": [],
   "source": [
    "Q = alg.rate(pores=pn.pores('back'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To find K, we need to solve Darcy's law: Q = KA/(mu*L)(P_in - P_out).  This requires knowing the viscosity and macroscopic network dimensions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.748594Z",
     "iopub.status.busy": "2021-06-24T11:25:10.748021Z",
     "iopub.status.idle": "2021-06-24T11:25:10.750308Z",
     "shell.execute_reply": "2021-06-24T11:25:10.749736Z"
    }
   },
   "outputs": [],
   "source": [
    "mu = np.mean(water['pore.viscosity'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The dimensions of the network can be determined manually from the ``shape`` and ``spacing`` specified during its generation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.753552Z",
     "iopub.status.busy": "2021-06-24T11:25:10.752978Z",
     "iopub.status.idle": "2021-06-24T11:25:10.755201Z",
     "shell.execute_reply": "2021-06-24T11:25:10.754703Z"
    }
   },
   "outputs": [],
   "source": [
    "L = 20 * 0.0001\n",
    "A = 20 * 10 * (0.0001**2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The pressure drop was specified as 1 atm when setting boundary conditions, so ``Kxx`` can be found as:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.758577Z",
     "iopub.status.busy": "2021-06-24T11:25:10.758009Z",
     "iopub.status.idle": "2021-06-24T11:25:10.760324Z",
     "shell.execute_reply": "2021-06-24T11:25:10.759823Z"
    }
   },
   "outputs": [],
   "source": [
    "Kxx = Q * mu * L / (A * 101325)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can either create 2 new **Algorithm** objects to perform the simulations in the other two directions, or reuse ``alg`` by adjusting the boundary conditions and re-running it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.763985Z",
     "iopub.status.busy": "2021-06-24T11:25:10.763425Z",
     "iopub.status.idle": "2021-06-24T11:25:10.765682Z",
     "shell.execute_reply": "2021-06-24T11:25:10.766138Z"
    }
   },
   "outputs": [],
   "source": [
    "alg.set_value_BC(values=202650, pores=pn.pores('left'))\n",
    "alg.set_value_BC(values=101325, pores=pn.pores('right'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.769569Z",
     "iopub.status.busy": "2021-06-24T11:25:10.768866Z",
     "iopub.status.idle": "2021-06-24T11:25:10.837468Z",
     "shell.execute_reply": "2021-06-24T11:25:10.836907Z"
    }
   },
   "outputs": [],
   "source": [
    "alg.run()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The first call to ``set_boundary_conditions`` used the ``overwrite`` mode, which replaces all existing boundary conditions on the ``alg`` object with the specified values.  The second call uses the ``merge`` mode which adds new boundary conditions to any already present, which is the default behavior.\n",
    "\n",
    "A new value for the flow rate must be recalculated, but all other parameters are equal to the X-direction:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.841528Z",
     "iopub.status.busy": "2021-06-24T11:25:10.840972Z",
     "iopub.status.idle": "2021-06-24T11:25:10.848359Z",
     "shell.execute_reply": "2021-06-24T11:25:10.848818Z"
    }
   },
   "outputs": [],
   "source": [
    "Q = alg.rate(pores=pn.pores('left'))\n",
    "Kyy = Q * mu * L / (A * 101325)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The values of ``Kxx`` and ``Kyy`` should be nearly identical since both these two directions are parallel to the small surface pores.  For the Z-direction:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.852365Z",
     "iopub.status.busy": "2021-06-24T11:25:10.851804Z",
     "iopub.status.idle": "2021-06-24T11:25:10.906234Z",
     "shell.execute_reply": "2021-06-24T11:25:10.906808Z"
    }
   },
   "outputs": [],
   "source": [
    "alg.set_value_BC(values=202650, pores=pn.pores('top'))\n",
    "alg.set_value_BC(values=101325, pores=pn.pores('bottom'))\n",
    "alg.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.911368Z",
     "iopub.status.busy": "2021-06-24T11:25:10.910700Z",
     "iopub.status.idle": "2021-06-24T11:25:10.918693Z",
     "shell.execute_reply": "2021-06-24T11:25:10.918133Z"
    }
   },
   "outputs": [],
   "source": [
    "Q = alg.rate(pores=pn.pores('top'))\n",
    "L = 10 * 0.0001\n",
    "A = 20 * 20 * (0.0001**2)\n",
    "Kzz = Q * mu * L / (A * 101325)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The permeability in the Z-direction is about half that in the other two directions due to the constrictions caused by the small surface pores."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-06-24T11:25:10.923016Z",
     "iopub.status.busy": "2021-06-24T11:25:10.922369Z",
     "iopub.status.idle": "2021-06-24T11:25:10.924619Z",
     "shell.execute_reply": "2021-06-24T11:25:10.925153Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[6.83485807e-11] [1.68157537e-10] [1.14203185e-10]\n"
     ]
    }
   ],
   "source": [
    "print(Kxx, Kyy, Kzz)"
   ]
  }
 ],
 "metadata": {
  "@webio": {
   "lastCommId": null,
   "lastKernelId": null
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
